package logic

import (
	"activity/models/cache"
	"activity/pkg"
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"time"

	"activity/activityRpc/activityRpc"
	"activity/activityRpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *activityRpc.SendSmsRequest) (*activityRpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "sendSmsNum"+in.Tel).Result()
	if result >= "1" {
		return nil, fmt.Errorf("当前验证码一分钟内只能发送一次")
	}

	code := rand.Intn(9000) + 1000

	sms, err := pkg.SendSms(in.Tel, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}

	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf(*sms.Body.Code)
	}

	cache.Rdb.Set(l.ctx, "sendSms"+in.Tel, code, time.Minute*3)

	incr := cache.Rdb.Incr(l.ctx, "sendSmsNum"+in.Tel)

	if incr.Val() == 1 {
		cache.Rdb.Expire(l.ctx, "sendSmsNum"+in.Tel, time.Minute*1)
	}

	return &activityRpc.SendSmsResponse{}, nil
}
